package net.caixiaomi.info.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.helper.AppHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 */
public class FileHelper {

    private static String folderName;

    public static void initFolderName(String fName) {
        folderName = Environment.getExternalStorageDirectory() + "/" + fName;
    }

    public static File folderName() {
        File file = new File(folderName);
        if (!file.exists())
            file.mkdir();
        return file;
    }

    private static String getPng(String path) {
        return path + ".png";
    }

    public static String generateFileName(String packageName) {
        return getPng(packageName);
    }

    public static File generateFile(String path) {
        File file = new File(folderName, ".nomedia");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                file.mkdir();
            }
        }
        return new File(folderName(), generateFileName(path));
    }

    /**
     * 返回SD卡根路径
     *
     * @return
     */
    public static String getSdcardRoot() {

        String retDir = "";
        try {
            File dir = isSdcardReady() ? Environment.getExternalStoragePublicDirectory(Constants.ROOT_FILE) : CommonApp.getInstance().getExternalFilesDir(Constants.ROOT_FILE);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            retDir = dir.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            retDir = "";
        }
        return retDir;
    }

    /**
     * 判断SD卡是否存在
     *
     * @return
     */
    public static boolean isSdcardReady() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    public static File getOutputMediaFile() {

        File mediaStorageDir = new File(getSdcardRoot(), Constants.DIR_FILE_TEMP_PIC);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(mediaStorageDir.getPath()).append(File.separator).append(Constants.IMG_PER).append(".png");
        String name = stringBuilder.toString();
        File mediaFile = new File(name);
        if(mediaFile.exists()){
            mediaFile.delete();
        }
        return mediaFile;
    }

    public static File getSavedFile(){

        File mediaStorageDir = new File(getSdcardRoot(), Constants.DIR_FILE_TEMP_PIC);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(mediaStorageDir.getPath()).append(File.separator).append(Constants.IMG_PER).append(".png");
        String name = stringBuilder.toString();
        File mediaFile = new File(name);
        return mediaFile;
    }



    /**
     * 保存bitmap至指定Picture文件夹
     */
    public static String saveBitmap(Context mContext, Bitmap bitmaptosave) {
        if (bitmaptosave == null)
            return null;
        File file;
        File mediaStorageDir = mContext.getExternalFilesDir("cxm");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        // String bitmapFileName = System.currentTimeMillis() + ".jpg";
        String bitmapFileName = System.currentTimeMillis() + "";
        file=new File(mediaStorageDir + "/" + bitmapFileName);
        if(file.exists()){
            file.delete();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);

            if (bitmaptosave.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
                fos.flush();
                fos.close();
// 插入图库
                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), file.getAbsolutePath(), bitmapFileName, null);
                mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mediaStorageDir + "/" + bitmapFileName)));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }



    /*
 * 保存文件，文件名为当前日期
 */
    public static void saveBitmap(Context mContext,Bitmap bitmap, String bitName){
        String fileName ;
        File file ;
        if(Build.BRAND .equals("Xiaomi") ){ // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+bitName+".png" ;
        }else{  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath()+"/DCIM/"+bitName+".png" ;
        }
        file = new File(fileName);

        if(file.exists()){
            file.delete();
        }
        FileOutputStream out;
        try{
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out))
            {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), file.getAbsolutePath(), bitName, null);

            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
            ToastUtil.s("保存失败");
        }
        catch (IOException e)
        {
            e.printStackTrace();
            ToastUtil.s("保存失败");
        }
        // 发送广播，通知刷新图库的显示
        mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));

    }
}
